package com.redpacketcover.rc.tabbar;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.MutableLiveData;

import com.redpacketcover.rc.Constants;
import com.redpacketcover.rc.MainActivity;
import com.redpacketcover.rc.R;
import com.redpacketcover.rc.base.BaseApplication;
import com.redpacketcover.rc.base.BaseResponseBean;
import com.redpacketcover.rc.base.ModelObserver;
import com.redpacketcover.rc.base.ObserverCallback;
import com.redpacketcover.rc.base.RetrofitManager;
import com.redpacketcover.rc.bean.GoodsRecord;
import com.redpacketcover.rc.goods.GoodsApiService;
import com.redpacketcover.rc.user.UserApiService;
import com.redpacketcover.rc.util.PreferencesUtil;
import com.redpacketcover.rc.util.SPUtils;
import com.redpacketcover.rc.util.UserInfo;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class TabMyFragment extends Fragment implements PlatformActionListener {

    private Context context;
    private Activity activity;
    private FragmentManager sFragmentManager;

    private TextView login_btn;
    private TextView user_title;

    private String openid;//  微信/QQ openId
    private String weChatData;

    public TabMyFragment(FragmentManager supportFragmentManager, MainActivity mainActivity) {
        super();
        this.activity = mainActivity;
        this.sFragmentManager = supportFragmentManager;
        this.context = mainActivity.getApplicationContext();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.my_layout,container,false);
        login_btn = view.findViewById(R.id.login_btn);
        user_title = view.findViewById(R.id.user_title);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        setListener();
    }

    private void initData() {
            HashMap<String, Object> params = new HashMap<>();
            UserApiService service = RetrofitManager.getInstance().create(UserApiService.class);
            Observable<BaseResponseBean<String>> observable = service.getUserInfo(params);
            DisposableObserver observer = new ObserverCallback<String>() {

                @Override
                public void onSuccess(String model) throws ParseException {

                }

                @Override
                public void onFailure(int code, String errMsg) {

                }
            };
            observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
    }

    private void setListener() {
        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Platform weixin = ShareSDK.getPlatform(Wechat.NAME);
                authorize(weixin);
            }
        });
    }

    private void authorize(cn.sharesdk.framework.Platform plat) {
        if (plat == null) {
            return;
        }
        //判断指定平台是否已经完成授权
        if (plat.isAuthValid()) {
            //执行此操作就可以移除掉本地授权状态和授权信息
            plat.removeAccount(true);
        }
        plat.setPlatformActionListener(this);
        // true不使用SSO授权，false使用SSO授权使用了SSO授权后，有客户端的都会优先启用客户端授权，没客户端的则任然使用网页版进行授权
        plat.SSOSetting(false);
        //获取用户资料
        plat.showUser(null);
    }

    @Override
    public void onComplete(cn.sharesdk.framework.Platform platform, int i, HashMap<String, Object> hashMap) {
        weChatData = platform.getDb().exportData();//取到所有数据
        openid = platform.getDb().getUserId();
        Log.w("TAG", "-map---------" + hashMap);
        PreferencesUtil.putString(context, "openid", openid);
        if (weChatData != null) {
            Message message = new Message();
            mHandler.sendMessage(message);
        }
    }

    //要用Handler回到主线程操作UI，否则会报错
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            initData();
        }
    };

    @Override
    public void onError(cn.sharesdk.framework.Platform platform, int i, Throwable throwable) {

    }

    @Override
    public void onCancel(cn.sharesdk.framework.Platform platform, int i) {

    }
}
